package two_shang._11_23;

public class ProerAndCuser {
    public static void main(String[] args) {
        Product product = new Product();
        Producter producter = new Producter(product);
        Customer customer = new Customer(product);
        Thread thread1 = new Thread(producter, "生产者");
        Thread thread2 = new Thread(customer, "消费者");
        thread1.start();
        thread2.start();
    }
}


class Product {
    private int count = 0;// 产品的计数器
    private String name;
    private boolean flag = false;

    // set生产的方法
    public synchronized void set(String name) {
        //设置退出条件
        if (this.count == 1000)
            System.exit(0);


        while (flag) {
            try {
                wait();
            } catch (Exception e) {
            }
        }
        this.name = name + count++;// 鼠标0
        System.out.println(Thread.currentThread().getName() + "生产了第"
                + this.name + "个鼠标===========");
        flag = true;
        notifyAll();
    }

    // get消费的方法
    public synchronized void get() {
        while (flag == false) {
            try {
                wait();
            } catch (Exception e) {
            }
        }
        System.out.println(Thread.currentThread().getName() + "消费了第"
                + this.name + "个鼠标");
        flag = false;
        notifyAll();
    }
}

// 生产者类
class Producter implements Runnable {
    private Product p;

    Producter(Product p) {
        this.p = p;
    }

    @Override
    public void run() {
        while (true) {
            p.set("鼠标");
        }
    }
}

// 消费者类
class Customer implements Runnable {
    private Product p;

    Customer(Product p) {
        this.p = p;
    }

    public void run() {
        while (true) {
            p.get();
        }
    }
}
